import Blender, sys, bpy, os

class BlenderImport(object):
    
    def __init__(self, obj3D, dirPath):
	
	self.obj3D = obj3D
	self.dirPath = dirPath
	
    def add_texture(self, material, matNum):
	
	texName = self.obj3D.get_material_texture(matNum)
	texture = Blender.Texture.New(texName)
	texture.setType("Image")
	
	texPath = os.path.join(self.dirPath, texName)	
	#check if image already exists
	try:
	    img = Blender.Image.get(texName)
	    texture.image = img
	    material.setTexture(0,texture,texture.TexCo.UV, texture.MapTo.COL)
	    #material.setTexture(0, texture)
	    #print "found image %s" %texName
	except:
	    #Does not exist. Try to load it
	    #try:
	    img = Blender.Image.Load(texPath) 
	    texture.image = img
	    material.setTexture(0,texture,Blender.Texture.TexCo.UV,Blender.Texture.MapTo.COL)
		#material.setTexture(0, texture)
	    #except:
		#print "couldn't load image: %s" %texName
	    #print "Created new image", img
	    
    def add_vertex_uv(self, mesh, meshName):
	
	mesh.vertexUV = 1
	for i in xrange(len(mesh.verts)):
	    uv = self.obj3D.get_vert_uv(meshName, i)
	    mesh.verts[i].uvco = Blender.Mathutils.Vector(uv)
	mesh.update()
    
    def add_face_uv(self, mesh, meshName):
	
	mesh.faceUV = 1
	for face in mesh.faces:
	    face.uv = [vert.uvco for vert in face.verts]
	    #face.smooth = 1
	mesh.update()
	    
    def add_material(self, mesh, matNum):
	
	matName = self.obj3D.get_material_name(matNum)
	material = Blender.Material.New(matName)
	self.add_texture(material, matNum)

	print material.textures
	mesh.materials.append(material)
	mesh.update()
	
    def add_face_material(self, mesh, meshName):
	
	for i in xrange(len(mesh.faces)):
	    matNum = self.obj3D.get_face_mat(meshName, i)
	    mesh.faces[i].mat = matNum
	
    def draw_mesh(self):
	
	objects = self.obj3D.get_objects()
	for meshName in objects:
	    mesh = bpy.data.meshes.new(meshName)
	    print "drawing", meshName
	    
	    numVerts = self.obj3D.vert_count(meshName)
	    vertices = []
	    for i in xrange(numVerts):
		coords = self.obj3D.get_coords(meshName, i)
		vertices.append(coords)
	    
	    numFaces = self.obj3D.face_count(meshName)
	    faces = []
	    for i in xrange(numFaces):
		vertList = self.obj3D.get_face_verts(meshName, i)
		faces.append(vertList)
	    
	    mesh.verts.extend(vertices)
	    mesh.faces.extend(faces,ignoreDups=True)
	    
	    matNum = self.obj3D.get_face_mat(meshName, 0)	    
	    self.add_material(mesh, matNum)
	    self.add_vertex_uv(mesh, meshName)
	    self.add_face_uv(mesh, meshName)
	    self.add_face_material(mesh, meshName)
		
	    scene = bpy.data.scenes.active
	    obj = scene.objects.new(mesh,meshName)
	    mesh.update()
	    Blender.Window.RedrawAll()

class BlenderExport(object):
    '''Takes all of the data from a blender object and create a model3D
    object'''